//
//  RecordViewController.m
//  VideoDiaryClass
//
//  Created by Wang Haitao on 15/10/19.
//  Copyright © 2015年 qianfeng. All rights reserved.
//

#import <AVFoundation/AVFoundation.h>

#import "RecordViewController.h"
#import "AVPlayerDemoPlaybackView.h"
#import "DiaryFile.h"
#import "InfoViewController.h"
#import "VideoCore.h"
#import "MBProgressHUD.h"

#define MAX_RECORD_TIME     20.
#define MIN_RECORD_TIME     2


@interface RecordViewController ()<VideoCoreDelegate>
{
    __weak IBOutlet UIView *videoView;
    __weak IBOutlet UIButton *playButton;
    __weak IBOutlet UIProgressView *progressView;
    
    __weak IBOutlet UIButton *recordButton;
    __weak IBOutlet UIButton *cameraButton;
    __weak IBOutlet UIButton *acceptButton;
    
    NSTimer * playTimer;
    NSTimer * recordTimer;
    
    NSDate * startRecordTime;
    BOOL invalidRecord;
}

@property (nonatomic) Diary * diary;
@property (nonatomic) AVPlayer * player;
@property (nonatomic) VideoCore * videoRecorder;
@property (nonatomic) MBProgressHUD * hud;


@end

@implementation RecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self checkDeviceAuthorizationStatus];

    playButton.hidden = YES;
    
    self.diary = [Diary new];
    
    self.videoRecorder = [[VideoCore alloc] initWithDelegate:self];
    [self.videoRecorder setCameraAtView:videoView];
    
    UILongPressGestureRecognizer * gesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(recordButtonLongPressed:)];
    gesture.minimumPressDuration = 0.5;
    [recordButton addGestureRecognizer:gesture];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self.videoRecorder startCamera];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) recordButtonLongPressed: (UILongPressGestureRecognizer *)gesture
{
    if (gesture.state==UIGestureRecognizerStateBegan) {
        invalidRecord = YES;
        self.diary.createDate = [NSDate date];
        [self.videoRecorder startRecordToPath:self.diary.videoPath];
    }
    else if(gesture.state==UIGestureRecognizerStateEnded) {
        [self.videoRecorder stopRecord];
        if (invalidRecord) {
            NSLog(@"User Record is invalid");
        }
        if ([recordTimer isValid]) {
            [recordTimer invalidate];
        }
    }
}

- (void)videoCoreStartRecording: (VideoCore *)videoCore
{
    recordTimer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(onRecordTimer:) userInfo:nil repeats:YES];
    
    startRecordTime = [NSDate date];
}

- (void)videoCoreFinishRecording: (VideoCore *)videoCore
{
    if (self.hud==nil) {
        self.hud = [[MBProgressHUD alloc] initWithView:self.view];
        self.hud.labelText = @"Please Wait...";
        [self.view addSubview:self.hud];
    }
    
    [self.hud show:YES];
    
    [self.videoRecorder cropVideo];
    
}

- (void)videoCoreFinishCropping: (VideoCore *)videoCore
{
    [self.hud hide:YES];
    
    [self.videoRecorder stopCamera];
    playButton.hidden = NO;
    [videoView bringSubviewToFront:playButton];
    
}

- (void) onRecordTimer: (NSTimer *) timer
{
    NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:startRecordTime];
    progressView.progress = interval / MAX_RECORD_TIME;
    
    if (interval>MIN_RECORD_TIME) {
        invalidRecord = NO;
    }
    if (interval>MAX_RECORD_TIME) {
        [timer invalidate];
        [self.videoRecorder stopRecord];
    }
}

- (IBAction)cancelButtonClicked:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (IBAction)acceptButtonClick:(id)sender
{
    NSLog(@"%@",startRecordTime);
    if(startRecordTime == NULL)
    {
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil
                                                                        message:@"You do not have to record video!" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"Cancel"
                                                  style:UIAlertActionStyleCancel
                                                handler:^(UIAlertAction * _Nonnull action) {
                                                    
                                                }]];
        
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (IBAction)playButtonClicked:(id)sender
{
    [self playVideo];
}

- (IBAction)cameraButtonClicked:(id)sender
{
    [self.videoRecorder changeCamera];
}

- (void) playVideo
{
    AVPlayerItem * playerItem = [[AVPlayerItem alloc] initWithURL:[NSURL fileURLWithPath:self.diary.videoPath]];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(videoPlayCompleted:)
                                                 name:AVPlayerItemDidPlayToEndTimeNotification
                                               object:playerItem];
    
    self.player = [AVPlayer playerWithPlayerItem:playerItem];
    
    AVPlayerDemoPlaybackView * playbackView = [[AVPlayerDemoPlaybackView alloc ] initWithFrame:videoView.bounds];
    
    playbackView.player = self.player;
    [videoView addSubview:playbackView];
    
    playTimer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(onPlayerTimer:) userInfo:nil repeats:YES];
    
    progressView.progress = 0;

    playButton.hidden = YES;
    
    [self.player play];
}

- (void) onPlayerTimer: (NSTimer *)timer
{
    CMTime playTime = [self.player currentTime];
    float currentSeconds = CMTimeGetSeconds(playTime);
    progressView.progress = currentSeconds / self.diary.duration;
}

#pragma mark -- 播放完成
- (void) videoPlayCompleted: (NSNotification *) notify
{
    [playTimer invalidate];
    playButton.hidden = NO;
    [videoView bringSubviewToFront:playButton];
}

#pragma mark -- 是否拥有使用摄像头的权限
- (void)checkDeviceAuthorizationStatus
{
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        if (granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                //                [self performSelector:@selector(startCamera) withObject:nil afterDelay:0.5];
            });
        }
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil
                                                                                message:@"No permission to use Camera, please change privacy settings" preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"Cancel"
                                                          style:UIAlertActionStyleCancel
                                                        handler:^(UIAlertAction * _Nonnull action) {
                                                            [self cancelButtonClicked:nil];
                                                        }]];
                
                [self presentViewController:alert animated:YES completion:nil];
            });
        }
    }];
}



#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    
    
        if ([segue.identifier isEqualToString:@"ShowProp"]) {
            InfoViewController * vc = segue.destinationViewController;
            vc.diary = self.diary;
        }
    
}


@end
